/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014-2016 abel533@gmail.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package tk.mybatis.springboot.api.controller;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import net.sf.json.JSONObject;
import tk.mybatis.springboot.mapper.TUserprofilePn2mMapper;
import tk.mybatis.springboot.model.Jforum;
import tk.mybatis.springboot.model.Message;
import tk.mybatis.springboot.model.Subjsct;
import tk.mybatis.springboot.model.TUserprofilePn2m;
import tk.mybatis.springboot.service.DianxinService;
import tk.mybatis.springboot.service.WexinInsuranceService;
import tk.mybatis.springboot.share.util.PropertiesUtil;
import tk.mybatis.springboot.wexin.bean.AccessToken;
import tk.mybatis.springboot.wexin.bean.JsapiTicket;
import tk.mybatis.springboot.wexin.bean.Userinfo;
import tk.mybatis.springboot.wexin.service.CoreService;
import tk.mybatis.springboot.wexin.service.WeixinService;
import tk.mybatis.springboot.wexin.util.ShaUtils;
import tk.mybatis.springboot.wexin.util.StringUtils;
import tk.mybatis.springboot.wexin.util.WeixinUtil;

/**
 * @author liujh
 */
@Controller
@RequestMapping("/weixin")
public class WexinController extends BaseController{

    @Autowired
    CoreService coreService;
    @Autowired
    WeixinService weixinService;
    @Autowired
    DianxinService dianxinService;
    @Autowired
	private WexinInsuranceService wexinInsuranceService;
    
	@Autowired
	private TUserprofilePn2mMapper tUserprofilePn2mMapper;
    
    @RequestMapping(method = RequestMethod.GET, value = "WeixinAccess")
    @ResponseBody
    public void wexin(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
    	coreService.wexGet(request, response);
    }
    //微信菜单回掉
    @RequestMapping(method = RequestMethod.POST, value = "WeixinAccess")
    @ResponseBody
    public String wexin2(HttpServletRequest request, HttpServletResponse response)throws Exception {
    	return coreService.processRequest(request,response);
    }
    
    //微信菜单回掉
    @RequestMapping(value = "createMenu")
    @ResponseBody
    public JSONObject createMenu(HttpServletRequest request, HttpServletResponse response)throws Exception {
    	return weixinService.createMenu();
    }
    
    @RequestMapping(value = "user")
    @ResponseBody
    public void user(HttpServletRequest request, HttpServletResponse response, String state, String code)throws Exception {  	
    	AccessToken accessToken = WeixinUtil.getAccessToken(code);
    	Userinfo userinfo = WeixinUtil.getUserinfo(accessToken);
    	HttpSession session = request.getSession();
    	session.setAttribute("userinfo", userinfo);
    	if("newcampaign".equals(state)) {
    		response.sendRedirect("http://wx.ydche.com/eInsurance/actlist.html");
    	} else if ("personcenter".equals(state)) {
    		response.sendRedirect("http://wx.ydche.com/eInsurance/share.html");
    	} else if ("shareinterest".equals(state)) {
    		response.sendRedirect("http://wx.ydche.com/eInsurance/eShare/share.html");
    	} else if ("dianxinfuli".equals(state)) {
    		response.sendRedirect("http://wx.ydche.com/eInsurance/eSingle/dxCardFree.html");
    	} else if("insurance".equals(state)){
    		response.sendRedirect("http://wx.ydche.com/yd/index.html");
    	} else if("pay".equals(state)){
    		response.sendRedirect("http://wx.ydche.com/eInsurance/payment.html");
    	} else if("zhangli".equals(state)){
			TUserprofilePn2m tUserprofilePn2m = new TUserprofilePn2m();
			tUserprofilePn2m.setValtype("varchar");
			tUserprofilePn2m.setKeyname("openid");
			tUserprofilePn2m.setValdata(userinfo.getOpenid());
			List<TUserprofilePn2m> select = tUserprofilePn2mMapper.select(tUserprofilePn2m);
			if(select.size() == 0){
				response.sendRedirect("http://wx.ydche.com/eInsurance/eBoon/boonbind.html?type=1");
				return;
			}
			session.setAttribute("user_id", select.get(0).getUser_id());
    		response.sendRedirect("http://wx.ydche.com/eInsurance/eBiz/bizhome.html");
    	} else if("zhangli2".equals(state)){
			TUserprofilePn2m tUserprofilePn2m = new TUserprofilePn2m();
			tUserprofilePn2m.setValtype("varchar");
			tUserprofilePn2m.setKeyname("openid");
			tUserprofilePn2m.setValdata(userinfo.getOpenid());
			List<TUserprofilePn2m> select = tUserprofilePn2mMapper.select(tUserprofilePn2m);
			if(select.size() == 0){
				response.sendRedirect("http://wx.ydche.com/eInsurance/eBoon/boonbind.html?type=2");
				return;
			}
			session.setAttribute("user_id", select.get(0).getUser_id());
    		response.sendRedirect("http://wx.ydche.com/eInsurance/eHome/selfinfo.html");
    	}
    }
    
    @RequestMapping(value = "user/getPersonInfo")
    @ResponseBody
    public Message getPersonInfo(HttpServletRequest request, HttpServletResponse response, String state, String code)throws Exception {  	
    	HttpSession session = request.getSession();
    	Userinfo userinfo = (Userinfo)session.getAttribute("userinfo");
    	return success("成功",userinfo);
    }
    
    @RequestMapping(value = "campaign/dianxin/playerInfo")
    @ResponseBody
    public JSONObject playerInfo(HttpServletRequest request, HttpServletResponse response, String userName)throws Exception {  	
    	HttpSession session = request.getSession();
    	Userinfo userinfo = (Userinfo)session.getAttribute("userinfo");
        return dianxinService.getDianxin(userinfo.getOpenid(), request.getParameter("userName"), request.getParameter("phoneNum"), request.getParameter("idCard"), 
    			request.getParameter("giftCard"), request.getParameter("minuteAdd"), request.getParameter("postCode"));
    }
    
    @RequestMapping(method = RequestMethod.GET, value = "sign/getSignature")
    @ResponseBody
    public Message getSignature(HttpServletRequest request, HttpServletResponse response, String url)throws Exception {
    	String jsapi_ticket = WeixinUtil.getJsapiTicket();
    	String noncestr = StringUtils.getRandomString(16);
    	String timestamp = String.valueOf(new Date().getTime());
    	Map<String,Object> map = new HashMap<String,Object>();
    	map.put("jsapi_ticket", jsapi_ticket.trim());
    	map.put("noncestr", noncestr);
    	map.put("timestamp", timestamp);
    	map.put("url", url);
    	String signature = ShaUtils.SHA1(map);
    	JsapiTicket JsapiTicket = new JsapiTicket();
    	JsapiTicket.setNonceStr(noncestr);
    	JsapiTicket.setSignature(signature);
    	JsapiTicket.setTimestamp(timestamp);
    	JsapiTicket.setAppID(PropertiesUtil.getMessage("appId"));
    	return success("成功", JsapiTicket);
    }
    
    @RequestMapping(method = RequestMethod.GET, value = "subject/list")
    @ResponseBody
    public Message getSubjectList(HttpServletRequest request, HttpServletResponse response, String row, String page)throws Exception {
    	List<Subjsct> subjscts= dianxinService.getSubjectList(row, page);
    	return success("成功", subjscts);
    }
    
    @RequestMapping(method = RequestMethod.GET, value = "subject/text")
    @ResponseBody
    public Message getSubjectText(HttpServletRequest request, HttpServletResponse response, String subjectID)throws Exception {
    	Jforum jforum = dianxinService.getSubjectText(subjectID);
    	return success("成功", jforum);
    }
    
    @RequestMapping(method = RequestMethod.GET, value = "bind/getStatus")
    @ResponseBody
    public Message getStatus(HttpServletRequest request, HttpServletResponse response)throws Exception {
    	HttpSession session = request.getSession();
    	Userinfo userinfo = (Userinfo)session.getAttribute("userinfo");
    	Boolean state = dianxinService.getStatus(userinfo.getOpenid());
    	return success("成功", state);
    }
    
    @RequestMapping(method = RequestMethod.GET, value = "bind/verifyCode")
    @ResponseBody
    public Message verifyCode(HttpServletRequest request, HttpServletResponse response, String mobile, String code)throws Exception {
    	return dianxinService.verifyCode(request, mobile, code);
    }
    
    @RequestMapping(method = RequestMethod.GET, value = "bind/sendCode")
    @ResponseBody
    public Message sendCode(HttpServletRequest request, HttpServletResponse response, String mobile)throws Exception {
    	return wexinInsuranceService.send(mobile);
    }
    
    @RequestMapping(method = RequestMethod.GET, value = "user/getMobile")
    @ResponseBody
    public Message getMobile(HttpServletRequest request, HttpServletResponse response)throws Exception {
    	HttpSession session = request.getSession();
    	Userinfo userinfo = (Userinfo)session.getAttribute("userinfo");
    	String phone = dianxinService.getMobile(userinfo.getOpenid());
    	return success("成功", phone);
    }
}
